<template>
  <div class="container">
    <div class="header">

      <div class="btn" @click="randomEvent">随机生成</div>
    </div>


    <div class="wrapper" ref="wrapper">
      <div id="svg-container"></div>
      <div class="left">
        <div v-for="item in leftNum" class="item" :key="item" ref="lefts">左{{ item }}</div>

      </div>
      <div class="right">
        <div v-for="item in rightNum" class="item" :key="item" ref="rights">右{{ item }}</div>
      </div>


    </div>

  </div>

</template>

<script>
import { SVG } from '@svgdotjs/svg.js'
import createNum from './utils/createNum';
import getPoints from './utils/getPoints';
import drawLines from './utils/drawLines';
import creatIndex from './utils/creatIndex';
// svg 实例
let draw = null

export default {
  data() {
    return {
      leftNum: 10,
      rightNum: 3,
      leftPoints: [],
      rightPoints: [],
    }
  },
  methods: {
    async randomEvent() {
      // [1] 生成 左右两边的个数
      let [leftNum, rightNum] = createNum()

      this.leftNum = leftNum
      this.rightNum = rightNum

      // 等渲染元素，才能拿到最新的元素dom
      await this.$nextTick()

      // [2] 生成要连线的索引
      let [leftIndexs, rightIndexs] = creatIndex(leftNum, rightNum)

      // [3] 计算开始点和结束点
      let [leftPoints, rightPoints] = getPoints(this.$refs.wrapper, this.$refs.lefts, this.$refs.rights, leftIndexs, rightIndexs)

      // [4] 画线
      drawLines(leftPoints, rightPoints, draw)
    }
  },
  mounted() {
    // 在mounted钩子中初始化svg.js
    draw = SVG().addTo('#svg-container').size('100%', '100%');

    this.$nextTick(() => {
      this.randomEvent()
    })

  }
}
</script>



<style>
.container {
  width: 1200px;
  margin: 40px auto 0 auto;
}

.header {
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.btn {
  padding: 6px 10px;
  user-select: none;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn:hover {
  background-color: #eee;

}

.wrapper {
  width: 100%;
  /* overflow: auto; */
  display: flex;
  justify-content: space-between;
  position: relative;
}

.item {
  width: 200px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  margin-bottom: 10px;
  background-color: aliceblue;
}

#svg-container {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;

}
</style>
